#include "loginwindow.h"
#include "ui_loginwindow.h"
#include <QPushButton>
#include <QDebug>
#include <QMessageBox>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQueryModel>
#include <QtSql/QSqlQuery>
#include <QKeyEvent>

loginWindow::loginWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::loginWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("心灵账本");
    //设置默认定位
    ui->logRegSwitch->setCurrentIndex(0);
    ui->nameEdit->setFocus();
    //登录注册按钮
    this->setStyleSheet("QPushButton{"
                        "border:2px solid rgb(169,171,181);"
                        "background: transparent;"
                        "border-radius: 4px;"
                        "color:rgb(0,0,0);}"
                        "QPushButton:hover{"
                        "background-color: rgb(169,171,181);"
                        "color:white;"
                        "border:2px solid rgb(255,255,255);}");
    //连接数据库
    connectUserDatabase();
    //登录按钮
    void (loginWindow:: * loginSignal)(QString user) = &loginWindow::loginSuccess;
    void (loginWindow:: * convertSignal)(QString user) = &loginWindow::convert;
    connect(ui->log_btn,&QPushButton::clicked,this,&loginWindow::login);
    connect(this,loginSignal,this,convertSignal);
    connect(this,&loginWindow::mainShow,[=](){
        mainWindow.mainCashBook();
        mainWindow.setLabel();
        mainWindow.changeTheme();
    });
    //将字母区回车键与登录和保存按钮绑定在一起
    ui->log_btn->setShortcut(Qt::Key_Return);
    ui->save_btn->setShortcut(Qt::Key_Return);
    //设置背景图
    ui->logRegSwitch->setAutoFillBackground(true); // 这句要加上, 否则可能显示不出背景图.
    QPalette palette = ui->logRegSwitch->palette();
    palette.setBrush(QPalette::Window,
                     QBrush(QPixmap(":/imageUsed/login.png").scaled( ui->logRegSwitch->size(),
                                                     Qt::IgnoreAspectRatio,
                                                     Qt::SmoothTransformation))); // 使用平滑的缩放方式
    ui->logRegSwitch->setPalette(palette); // 已给widget加上了背景图.
}

void loginWindow::keyPressEvent(QKeyEvent *e)
{
    switch(e->key())
    {
    case Qt::Key_Up :
    {
        if(ui->logRegSwitch->currentIndex()==0)
        {
            ui->nameEdit->setFocus();
        }
        else if(ui->logRegSwitch->currentIndex()==1)
        {
            if(ui->newNameEdit->hasFocus()||ui->newPasswordEdit->hasFocus())
            {
                ui->newNameEdit->setFocus();
            }
            else if(ui->setPasswordEdit->hasFocus())
            {
                ui->newPasswordEdit->setFocus();
            }
        }
        break;
    }
    case Qt::Key_Down :
    {
        if(ui->logRegSwitch->currentIndex()==0)
        {
            ui->passwordEdit->setFocus();
        }
        else if(ui->logRegSwitch->currentIndex()==1)
        {
            if(ui->newNameEdit->hasFocus())
            {
                ui->newPasswordEdit->setFocus();
            }
            else if(ui->newPasswordEdit->hasFocus()||ui->setPasswordEdit->hasFocus())
            {
                ui->setPasswordEdit->setFocus();
            }
        }
        break;
    }
    }
}

void loginWindow::convert(QString user)
{
    this->hide();
    mainWindow.show();
    mainWindow.setUser(user);
}

bool loginWindow::connectUserDatabase()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("81.70.27.194");//localhost 192.168.1.104
    db.setDatabaseName("cashbook");
    db.setUserName("root");
    db.setPassword("6274426");
    if(db.open())
    {
        qDebug()<<"连接成功！";
        return true;
    }
    else
    {
        qDebug()<<"连接失败！";
        return false;
    }
}

void loginWindow::login()
{
    QSqlQuery query,query_2;
    QString sql;
    QString str1 ,str2;
    str1 = ui->nameEdit->text();//用户输入的用户名
    str2 = ui->passwordEdit->text();//用户输入的密码
    if(str1==""||str2=="")
    {
        QMessageBox message(QMessageBox::NoIcon, "error", "用户名或密码为空！");
        message.exec();
        ui->nameEdit->clear();
        ui->passwordEdit->clear();
        return ;
    }
    sql = QString("select * from users where name = '%1'").arg(str1);
    query.exec(sql);
    while(query.next())
    {
        //获取该用户名下的密码进行对比
        if(query.value(2).toString()==str2)
        {
            //如果不存在登陆用户的表，则创建一个
            sql = QString("create table %1 (id int primary key AUTO_INCREMENT, "
                          "in_out varchar(255), money double, theme varchar(255), date_year int, date_month int, date_day int, "
                          "date_hour int, date_minute int, mood varchar(255), other varchar(255))").arg(str1);
            if (query_2.exec(sql))
            {
                    qDebug() << "Create table Successful";
            }
            else
            {
                    qDebug() << "Create table Fail";
            }
            qDebug()<<"userlogwindow:"<<str1.toUtf8();
            emit loginSuccess(str1);//传递成功登陆信号
            emit mainShow();
            //清空输入栏
            ui->nameEdit->clear();
            ui->passwordEdit->clear();
            return;
        }
        else
        {
            ui->passwordEdit->clear();
            QMessageBox message(QMessageBox::NoIcon, "error", "密码错误！");
            message.exec();
            qDebug()<<"密码错误";
            ui->passwordEdit->setFocus();
            return;
        }
    }
    ui->nameEdit->clear();
    ui->passwordEdit->clear();
    QMessageBox message(QMessageBox::NoIcon, " ", "用户名不存在！");
    message.exec();
    qDebug()<<"用户名不存在";
    ui->nameEdit->setFocus();
}

void loginWindow::saveToDatabase()
{
    QSqlQuery query1,query2;
    QString sql;
    QString str1 ,str2, str3;
    str1 = ui->newNameEdit->text();
    str2 = ui->newPasswordEdit->text();
    str3 = ui->setPasswordEdit->text();
    if(str1==""||str2=="")
    {
        QMessageBox message(QMessageBox::NoIcon, "error", "用户名或密码为空！");
        message.exec();
        ui->newNameEdit->clear();
        ui->newPasswordEdit->clear();
        ui->setPasswordEdit->clear();
        return ;
    }
    if (str2 != str3)
    {
        QMessageBox message(QMessageBox::NoIcon, "error", "两次密码不一致");
        message.exec();
        ui->newNameEdit->clear();
        ui->newPasswordEdit->clear();
        ui->setPasswordEdit->clear();
        return ;
    }
    sql = QString("select * from users where name = '%1'").arg(str1);
    query1.exec(sql);
    //如果这条数据不存在那么插入这条数据
    while(!query1.next())
    {
        sql = QString("insert into users(name, password) values('%1','%2')").arg(str1).arg(str2);
        qDebug()<<sql;
        query2.exec(sql);
        //debug测试
        query2.exec("select id,name,password from users");
        while(query2.next())
        {
            //query.value(0)是id的值
            //name
            str1 = query2.value(1).toString();
            //password
            str2 = query2.value(2).toString();
            //输出两个值
            qDebug() << str1<< str2;
        }
        QMessageBox message(QMessageBox::NoIcon, "", "注册成功");
        message.exec();
        qDebug()<<"注册成功";
        ui->newNameEdit->clear();
        ui->newPasswordEdit->clear();
        ui->setPasswordEdit->clear();
        return ;
    }
    qDebug()<<"用户已存在";
    ui->newNameEdit->clear();
    ui->newPasswordEdit->clear();
    ui->setPasswordEdit->clear();
    QMessageBox message(QMessageBox::NoIcon, "error", "用户名已存在");
    message.exec();
}

loginWindow::~loginWindow()
{
    delete ui;
}

void loginWindow::on_reg_btn_clicked()
{
    ui->logRegSwitch->setCurrentIndex(1);
    ui->newNameEdit->setFocus();
}

void loginWindow::on_save_btn_clicked()
{
    //将新用户名密码存储到users表中
    saveToDatabase();
    ui->logRegSwitch->setCurrentIndex(0);
    ui->nameEdit->setFocus();
}

void loginWindow::on_back_btn_clicked()
{
    ui->logRegSwitch->setCurrentIndex(0);
    ui->nameEdit->setFocus();
}
